package org.pupil.socket.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.pupil.common.*;
import org.pupil.common.constants.RpcProxy;
import org.pupil.proxy.IProxy;
import org.pupil.proxy.ProxyFactory;
import org.pupil.service.HelloService;
import org.pupil.socket.codec.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description: 服务发送方
 * @Author: pupil
 * @Date: 2024/07/09 下午 4:00
 */
public class Client {

    private Logger logger = LoggerFactory.getLogger(Client.class);

    private final String host;

    private final Integer port;

    private final Bootstrap bootstrap;
    private final EventLoopGroup eventLoopGroup;

    private ChannelFuture channelFuture;

    public Client(String host, Integer port) throws InterruptedException {
        this.host = host;
        this.port = port;

        bootstrap = new Bootstrap();
        eventLoopGroup = new NioEventLoopGroup(4);

        bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new RpcEncoder())
                                .addLast(new RpcDecoder())
                                .addLast(new ClientHandler());
                    }
                });
    }

    // 发送请求
    public void registerBean(String serviceName) {
        final URL url = new URL(host, port);
        Cache.services.put(new Service(serviceName), url);
        // 等待连接，连接成功后返回channelFuture用于通信
        channelFuture = bootstrap.connect(host, port);
        Cache.channelFutureMap.put(url, channelFuture);
    }

    public static void main(String[] args) throws Exception {
        // 创建服务发送方
        final Client client = new Client("127.0.0.1", 8081);
        // 进行服务请求注册
        client.registerBean(HelloService.class.getName());
        // 获取代理类工厂
        final IProxy iProxy = ProxyFactory.get(RpcProxy.CG_LIB);
        // 获取代理类
        final HelloService proxy = iProxy.getProxy(HelloService.class);
        System.out.println(proxy.hello("pupil~"));
    }
}
